﻿var numbers = '0123456789';
var lowerAlpha = 'abcdefghijklmnopqrstuvwxyz';
var upperAlpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function processText()
{
    writeTextModel(extractText());
}

function initializeNewWord()
{
    var result = new Object();
    result.text = "";
    result.prefix = "";
    result.postfix = "";

    return result;
}

function extractText()
{
    var textToExtract = $("#taInputText").val();

    var textModel = new Array();
    var word = initializeNewWord();

    for (var i = 0; i < textToExtract.length; i++)
    {
        var charAt = textToExtract.charAt(i);
        if ((word.text == "") && (!isAlpha(charAt)))
        {
            word.prefix += charAt;
        }
        else if ((word.text != "") && (!isAlpha(charAt)))
        {
            word.postfix += charAt;
        }
        else if ((word.text != "") && (word.postfix != "") && (isAlpha(charAt)))
        {
            textModel.push(word);
            word = initializeNewWord();
        }

        if (isAlpha(charAt))
        {
            word.text += charAt;
        }
    }

    if (word.text != "")
        textModel.push(word);

    return textModel;
}

function isLowerAlpha(c)
{
    return lowerAlpha.indexOf(c) != -1;
}

function isUpperlpha(c)
{
    return upperAlpha.indexOf(c) != -1;
}

function isAlpha(c)
{
    return isLowerAlpha(c) || isUpperlpha(c);
}

function writeTextModel(textModel)
{
    var divExtractedText = $("#divExtractedText");

    var html = "";
    for (var i = 0; i < textModel.length; i++)
    {
        html += renderWord(textModel[i]);
    }

    divExtractedText.html(html);
}

function renderWord(word)
{
    var result = word.prefix.replace("\n", "<br>");
    result += renderWordAsSpan(word);
    result += word.postfix.replace("\n", "<br>");
    return result;
}

function renderWordAsSpan(word)
{
    return "<span " + renderOnClcik(word) + ">" + word.text + "</span>";
}

function renderWordAsAnchor(word)
{
    return "<a href='#' " + renderOnClcik(word) + ">" + word.text + "</a>";
}

function renderOnClcik(word)
{
    return "onclick = '" + "alert(\"aaaaa\");'";
}